package com.amkai.aes.webservice.binary.objecthandler.inventory;

public class AdvancedHQLGenerator extends PropertyHQLGenerator {
	
	private static int count = 0;
	
	private String fetchPath;

	private String fetchAlias;

	private String fetchProperty;

	private PropertyHQLGenerator propertyGenerator;

	public AdvancedHQLGenerator(String instanceName, String propertyName,
			ResolverServiceManager resolverMgr) {
		super(instanceName, propertyName, resolverMgr);
	}

	@Override
	public String getHQLFragment() {
		if (propertyGenerator == null) return null;
		return propertyGenerator.getHQLFragment();
	}

	@Override
	public String getHQLPropertyName() {
		if (propertyGenerator == null) return null;
		return propertyGenerator.getHQLPropertyName();
	}

	@Override
	public Object getValueFromText(String searchText) {
		if (propertyGenerator == null) return null;
		return propertyGenerator.getValueFromText(searchText);
	}

	@Override
	public String getAdditionalFetchHQL() {
		return String.format("left outer join %s as %s", fetchPath, fetchAlias);
	}

	public void initialize(Class<?> itemClass, boolean caseSensitive,
			boolean exactMatch) {
		String[] properties = propertyName.split("\\.");
		StringBuilder sb = new StringBuilder(instanceName);
		for (int i=0; i<properties.length-1; i++) {
			sb.append('.');
			sb.append(properties[i]);
		}
		fetchPath = sb.toString();
		fetchAlias = generateAlias(properties[properties.length-2]);
		fetchProperty = properties[properties.length-1];
		propertyGenerator = PropertyHQLGeneratorFactory.getGenerator(itemClass, fetchPath, fetchProperty, resolverMgr, caseSensitive, exactMatch);
		//propertyGenerator = PropertyHQLGeneratorFactory.getGenerator(itemClass, fetchAlias, fetchProperty, resolverMgr, caseSensitive, exactMatch);
	}
	
	private String generateAlias(String property) {
		return String.format("%s_%02d", property, count++);
	}

}
